'''
    @author lifei
'''

import time
from app.Menu import main_menu
from util.DbUtils import DatabaseUtil
# 连接数据库
from util.Util import read_user, read_user_info
from wrapper.BalanceFlowWrapper import balance_flow_wrapper

db = DatabaseUtil(user="root",password="123456",database="woniuatm",port=3306)
#查询用户相关信息  name  **某： 余额为：
def query():
    from services.UserService import login_user_id
    sql = "select * from user where user_id ='%d'"%(login_user_id)
    print(db.select(sql))
    
# 存款
@balance_flow_wrapper
def deposite(user_index,op_type,money):
    save_history(user_index,op_type,money)
    change_balance(user_index,int(money))


#判断输入的金额 是否是数字
def check_number(money):
    return money.isdigit()
    
#修改更改存款后的余额    
def change_balance(user_index,money):
    old_balance = read_user_info(user_index)[0]['balance']
    print('old_balance',old_balance)
    sql = "update  user set balance = '%d' where user_id = '%d'"%(old_balance+money,user_index)
    db.update(sql)

    
# 取款
@balance_flow_wrapper
def withdraw(user_index,op_type,money):
    save_history(user_index,op_type,money)
    change_balance(user_index,int('-'+money))

#判断能否取款
def can_withdraw(money,login_user_id):
    balance=read_user_info(login_user_id)[0]['balance']
    return int(money) <= int(balance)
    
    
# 转账
def transfer():
    # 输入对方账号
    username = input("请输入收款方账户名称")
    # 判断账号是否存在
    # 如果不存在返回值为False
    from services.UserService import check_user
    to_index = check_user(username)
    print('收款方id',to_index)
    if to_index >= 0:
        # 输入转账金额
        money = int(input("请输入转账金额"))
        from services.UserService import login_user_id
        print('当前用户id',login_user_id)
        if check_balance(login_user_id,money):
            change_balance(login_user_id,money*-1)
            # 保存转账流水
            save_history(login_user_id,'转账',money)
            save_history(to_index,'到账',money)
            change_balance(to_index,money)
            main_menu('')
        else:
            print("金额不足,不可以转账,请先存款")
            deposite()
      
    else:
        print("对方账户不存在")
        transfer()
        
def check_balance(user_index,money):
    """
        检查余额是否足够!
    """
    sql = "select * from user where user_id ='%d'"%(user_index)
    result = db.select(sql)
    if int(result[0]['balance']) < money:
        return False
    else:
        return True       
        
#保存历史流水记录
def save_history(user_index,op_type,money):
    remark = op_type+": "+str(money)
    create_on = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    sql = "insert into billsflow(user_id,remark,create_on) values('%d','%s','%s')"%(user_index,remark,create_on)
    db.update(sql)

    
# 查询流水
def history():
    from services.UserService import login_user_id
    sql = "select * from billsflow where user_id ='%d'"%(login_user_id)
    print(db.select(sql))
    

